package com.lyy.config;


import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.amqp.core.Queue;

/**
 * @author Liangyaoyun
 */
@Configuration
public class DirectConfig implements BeanPostProcessor {

    /**
     * RabbitAdmin用来创建队列和交换机
     */
    @Autowired
    public RabbitAdmin rabbitMQAdmin;

    @Bean
    @ConditionalOnMissingBean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        //创建RabbitAdmin实例,并设置在项目启动时将该实例自动交给Spring管理
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        //设置自启动
        rabbitAdmin.setAutoStartup(true);
        return rabbitAdmin;
    }
    /**管理[direct直连模式]下的[队列A]*/
    @Bean
    public Queue directQueueA(){
        //参数分别对应：队列名，是否持久化，是否私有独占队列，是否无消费者是删除队列
        return new Queue("My_Queue_Name",true,false,false);
    }

    /**管理[direct直连模式]下的[交换机]*/
    @Bean
    public DirectExchange directExchange(){
        //参数分别对应：交换机名字，是否持久化，是否无消费者时删除交换机
        return new DirectExchange("My_Exchange_Name",true,false);
    }
    /**将[队列A] 绑定到指定[交换机] 并设置[路由键]*/
    @Bean
    public Binding bindDirectQueueA(){
        return BindingBuilder
                .bind(directQueueA())
                .to(directExchange())
                .with("My_Routing_Key");
    }

    /**Bean的后置处理器：在项目启动后执行，自动创建队列和交换机*/
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName){
        rabbitMQAdmin.declareQueue(directQueueA());
        rabbitMQAdmin.declareExchange(directExchange());
        return null;
    }


}
